package newx.com.control.radio
{
	import newx.NxSprite;
	
	public class NxRadioGroup extends newx.NxSprite
	{
		private var _nxRadioList:Array = [];
		
		private var _selectedNxRadio:NxRadio;
		
		private var _selectedIndex:int = -1;
		
		public function NxRadioGroup($nxRadioList:Array =null)
		{
			_nxRadioList = $nxRadioList; 
			
			init();
		}
		
		private function init():void
		{
			addListener();
		}
		
		public function addNxRadioList($nxRadioList:Array):void
		{
			_nxRadioList = [];
			_nxRadioList = $nxRadioList;
			
			reset();
		}
		
		public function clear():void
		{
			_nxRadioList = [];
			reset();
		}
		
		/**
		 * 添加radio 
		 * @param $nxRadio
		 * 
		 */
		public function addNxRadio($nxRadio:NxRadio):void
		{
			if(_nxRadioList == null){
				_nxRadioList	=	[];
			}
			_nxRadioList.push($nxRadio);
		}
		
		/**
		 * 删除radio 
		 * @param $nxRadio
		 * 
		 */
		public function removeNxRadio($nxRadio:NxRadio):void
		{
			var index:int = _nxRadioList.indexOf($nxRadio);
			if(index == -1)return;
			//当删除的是选择的radio
			if(index == _selectedIndex){
				reset();
			}
			_nxRadioList.splice(index,1);
		}
		
		/**
		 * 设置选中的Rodio下标 
		 * @param $index
		 */
		public function set selectedIndex($index:int):void
		{
			selectdNxRadio = _nxRadioList[$index];
			_selectedIndex	=	$index;
		}
		
		/**
		 * 获得 选中的Rodio下标 
		 * @return 
		 */
		public function get selectedIndex():int
		{
			return _selectedIndex;
		}
		
		/**
		 * 获得 选中的Rodio 
		 * @return 
		 */
		public function get selectedNxRadio():NxRadio
		{
			return _nxRadioList[_selectedIndex];
		}
		
		/**
		 * 设置选中的Rodio 
		 * @param $index
		 */
		public function set selectdNxRadio($value:NxRadio):void
		{
			$value.dispatchEvent(new NxRadioEvent(NxRadioEvent.RADIO_CLICK,$value));
		}

		private function onCLick(e:NxRadioEvent):void
		{
			var selectedNxRadio:NxRadio = e.nxRadio;
			selectedNxRadio.selected = true;
			
			var leng:int = _nxRadioList.length;
			for(var i:int = 0;i< leng;i++){
				var nxRadio:NxRadio = _nxRadioList[i];
				if(nxRadio != selectedNxRadio){
					nxRadio.selected = false;
				}else{
					_selectedIndex = i;
				}
			}
			this.dispatchEvent(new NxRadioEvent(NxRadioEvent.RADIO_GROUP_CLICK,selectedNxRadio));
		}
		
		public function reset():void
		{
			_selectedIndex = -1;
			_selectedNxRadio = null;
		}
		
		private function addListener():void
		{
			for each(var nxRadio:NxRadio in _nxRadioList){
				nxRadio.addEventListener(NxRadioEvent.RADIO_CLICK,onCLick);
			}
		}
		
		private function removeListener():void
		{
			for each(var nxRadio:NxRadio in _nxRadioList){
				nxRadio.removeEventListener(NxRadioEvent.RADIO_CLICK,onCLick);
			}
		}
	}
}